#include "writethread.h"
#include <errno.h>

WriteThread::WriteThread(int serialFD,QByteArray byteArray) : QThread(), m_serial(serialFD), m_dataArray(byteArray)
{
    sendFinishFlag=0;
}

WriteThread::~WriteThread()
{
    ::close(m_serial);
}

void WriteThread::run()
{
    SendData();
    exec();
}

void WriteThread::SendData()
{
    struct timeval timeout;
    int fd;
    int sentLen = 0;
    int totalLen = m_dataArray.size();
    
    while(sentLen < totalLen)
    {
	FD_ZERO(&m_writeSet);
	FD_SET(m_serial,&m_writeSet);
        timeout.tv_sec = 0;
	timeout.tv_usec = 500;
	
	fd = select(m_serial + 1, NULL,&m_writeSet, NULL, &timeout);
	if(fd > 0)
	{
	    if(FD_ISSET(m_serial,&m_writeSet) == 1)
	    {
		sentLen += write(m_serial,m_dataArray.data()+sentLen,totalLen-sentLen);
	    }
	}
    }
}
